package com.sumainfor.pc.market.service;

import com.alibaba.fastjson.JSONObject;
import com.sumainfor.common.config.RedisUtils;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.market.dao.RdHousingSmartMapper;
import com.sumainfor.pc.market.dao.RdHousingTemcodeMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 临时密码（每天只能申请三次）
 */
@Service
public class RdHousingTemcodeService implements Serializable {

    private ReentrantLock lock = new ReentrantLock(false);

    Logger log = LoggerFactory.getLogger(RdHousingTemcodeService.class);// 日志

    @Autowired
    private RdHousingTemcodeMapper rdHousingTemcodeMapper;
    @Autowired
    private RedisUtils redisUtils;
    /**
     * 给租客发送临时密码（每个租客每天只能发三次）
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addRdHouTemcode(Map<String,Object> params){
        System.out.println("params:"+params);
        JsonResult result=new JsonResult();
        if (params.get("IdentifierList")==null || params.get("HouId")==null || params.get("HouInfoId")==null
                || params.get("PaId")==null || params.get("TenId")==null){
            return result.putFailed("参数不正确");
        }
        //查询发送密钥的次数
        Integer temCount=rdHousingTemcodeMapper.getRdHouTemcodeCount(params);
        if (temCount==null){
            return result.putFailed("服务器繁忙");
        }else{
            params.put("TemCount",temCount);
        }
        //判断今天发送临时密码的次数是不是已经3次
        if(temCount>=3){
            return result.put(params);
        }else {
            System.out.println("租客端参数:" + params);
            List<Map<String, Object>> IdentifierList = (List<Map<String, Object>>) params.get("IdentifierList");
            int num = 0;
            int num2 = 0;//科技侠
            for (Map<String, Object> InteMap : IdentifierList) {
                //0.蜂电   1.大华   2.科技侠   3.果加
                if (InteMap.get("Intelligent").toString().equals("2")) {
                    String DeviceLockToken=redisUtils.get("DeviceLockToken");
                    //如果获取不到就重新登录
                    if (DeviceLockToken==null){
                        Map<String,Object> tokenMap=new HashMap<String, Object>();
                        params.put("client_id",InteDeviceLockConfig.CLIENT_ID);
                        params.put("client_secret",InteDeviceLockConfig.CLIENT_SECRET);
                        params.put("grant_type",InteDeviceLockConfig.GRANT_TYPE_PASSWORD);
                        params.put("username",InteDeviceLockConfig.USERNAME);
                        params.put("password",InteDeviceLockConfig.PASSWORD);
                        params.put("redirect_uri",InteDeviceLockConfig.REDIRECT_URL);
                        tokenMap=InteDeviceLockUtil.oauth2Token(params);
                        if (tokenMap.get("access_token")!=null){
                            DeviceLockToken=tokenMap.get("access_token").toString();
                            //token存到redis中
                            redisUtils.set("DeviceLockToken",DeviceLockToken,Long.valueOf(tokenMap.get("expires_in").toString()));
                        }else{
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return result.putFailed("token获取失败");
                        }
                    }
                    num2++;
                    params.put("clientId", InteDeviceLockConfig.CLIENT_ID);//应用编号
                    params.put("accessToken", DeviceLockToken);//访问令牌
                    params.put("lockId", InteMap.get("Identifier"));//智能设备编号
                    params.put("keyboardPwdVersion", "4");//键盘密码版本, 三代锁的密码版本为4
                    params.put("keyboardPwdType", "1");//参数值 单次	1
                    //密码有效时间
                    //获取当前时间
                    params.put("startDate", InteDeviceLockUtil.getTimeSign(InteDeviceLockUtil.getTimeAfter(System.currentTimeMillis(), 0, "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
                    //获取一个小时之后的时间
                    params.put("endDate", InteDeviceLockUtil.getTimeSign(InteDeviceLockUtil.getTimeAfter(System.currentTimeMillis(), 60 * 60 * 1000, "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
                    params.put("date", InteDeviceLockUtil.getTimeSign());
                    System.out.println("params:" + params);
                    Map<String, Object> map = InteDeviceLockUtil.keyboardPwdGet(params);
                    if (map.get("keyboardPwd") != null) {
                        InteMap.putAll(map);
                        num++;
                    } else {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return result.putFailed("服务器繁忙");
                    }
                    InteMap.putAll(map);
                }else if(InteMap.get("Intelligent").toString().equals("3")){
                    String GuoJiaToken=redisUtils.get("GuoJiaToken");
                    //如果获取不到就重新登录
                    if (GuoJiaToken==null){
                        Map<String,Object> guoJiaMap=new HashMap<String, Object>();
                        guoJiaMap.put("s_id",InteGuoJiaUtil.getSid());
                        guoJiaMap.put("version","1");
                        JSONObject bodyJson=new JSONObject();
                        //key
                        DESEncrypt desPlus2 = new DESEncrypt(InteGuoJiaConfig.DES_KEY);
                        //密码
                        bodyJson.put("account",InteGuoJiaConfig.ACCOUNT);
                        bodyJson.put("password",desPlus2.encrypt(InteGuoJiaConfig.PASSWORD));
                        guoJiaMap=InteGuoJiaUtil.login(guoJiaMap,bodyJson);
                        //返回的token数据
                        Map<String,Object>dataMap=(Map<String,Object>)guoJiaMap.get("data");
                        if (guoJiaMap.get("rlt_code").toString().equals("HH0000")){//HH0000 、成功
                            GuoJiaToken=dataMap.get("access_token").toString();
                            //token存到redis中
                            redisUtils.set("GuoJiaToken",GuoJiaToken,Long.valueOf(dataMap.get("expires_second").toString()));
                        }else{
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return result.putFailed("token获取失败");
                        }
                    }
                    num2++;
                    Map<String,Object> guoJiaMap=new HashMap<String, Object>();
                    guoJiaMap.put("s_id", InteGuoJiaUtil.getSid());
                    guoJiaMap.put("version","1");
                    guoJiaMap.put("access_token",GuoJiaToken);
                    JSONObject bodyJson=new JSONObject();
                    bodyJson.put("lock_no",InteMap.get("Identifier"));//智能设备编号
                    bodyJson.put("pwd_user_mobile","13020100801");
                    System.out.println("guoJiaMap:"+guoJiaMap);
                    //发送键密码
                    Map<String,Object> map=InteGuoJiaUtil.temp_pwd(guoJiaMap,bodyJson);
                    DESEncrypt desPlus2 = new DESEncrypt(InteGuoJiaConfig.DES_KEY);
                    String d2="";
                    try {
                        Map<String,Object> dataMap=(Map<String,Object>)map.get("data");
                        d2 = desPlus2.decrypt(DESEncrypt.byteArr2HexStr(DESEncrypt.hexStringToBytes(String.valueOf(dataMap.get("pwd_text")))));
                    }catch (Exception e){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        log.debug("键盘密码解密错误"+e);
                    }
                    if (map.get("rlt_code").toString().equals("HH0000")){//HH0000 请求成功
                        InteMap.put("keyboardPwd",d2);
                        InteMap.putAll(map);
                        num++;
                    }else{
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return result.putFailed("服务器繁忙");
                    }
                    InteMap.putAll(map);
                }
            }
            //组装租客申请临时密码记录参数
            Map<String, Object> TemMap = new HashMap<String, Object>();
            TemMap.put("by", "auto");//操作人
            TemMap.put("TemId", UUIDUtils.generateShortUuid());//UUID
            TemMap.put("HouId", params.get("HouId"));//房源编号
            TemMap.put("HouInfoId", params.get("HouInfoId"));//房源详表编号
            TemMap.put("PaId", params.get("PaId"));//合同编号
            TemMap.put("TenId", params.get("TenId"));//租客编号
            TemMap.put("delfg", 0);//租客编号
            TemMap.put("term", "1");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            TemMap.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonInsertParms(TemMap);
            TemMap.put("TemDate", TemMap.get("instm"));//申请时间
            //新增租客申请临时密码记录
            Integer count = rdHousingTemcodeMapper.addRdHouTemcode(TemMap);
            if (num == num2 && count > 0) {
                result.put(params);
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                result.putFailed("服务器繁忙");
            }
        }
        return result;
    }
    /**
     * 查询租客当天申请临时密码的次数
     */
    public JsonResult getRdHouTemcodeCount(Map<String,Object> params){
        JsonResult result=new JsonResult();
        if (params.get("TenId")==null){
            return result.putFailed("参数不正确");
        }
        Integer count=rdHousingTemcodeMapper.getRdHouTemcodeCount(params);
        if (count!=null){
            result.put(count);
        }else{
            result.putFailed("服务器繁忙");
        }
        return result;
    }
}
